<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        :placeholder="t('message.layout.title')"
        style="width: 100px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <!--
      <el-select
        v-model="listQuery.author"
        :placeholder="t('message.layout.managementUnit')"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      -->
      <!--
      <el-select
        v-model="listQuery.type"
        :placeholder="t('message.layout.type')"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item.key"
          :label="item.displayName + '(' + item.key + ')'"
          :value="item.key"
        />
      </el-select>
      -->
      
      <!--
      <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('message.layout.search') }}
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
      <!--
        {{ t("message.layout.add") }}
      -->
      地图添加
      </el-button>
      <!--
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        {{ t("message.layout.export") }}
      </el-button>      
      <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left: 15px"
        @change="tableKey = tableKey + 1"
      >
        {{ t("message.layout.reviewer") }}
      </el-checkbox> 
      -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
    <!--
      <el-table-column
        :label="t('message.layout.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template #default="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      -->
      <el-table-column
        :label="t('message.layout.title')"
        min-width="100px"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleUpdate(row)"
          >{{
            row.title
          }}</span>
          <!-- <el-tag>{{ row.type }}</el-tag> -->
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.phone')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.timestamp }}</span>
        </template>
      </el-table-column>      
      <!--
      <el-table-column
        :label="t('message.layout.author')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      -->
      <el-table-column
        :label="t('message.layout.reviewer')"
        width="110px"
        align="center"
      >
        <template #default="{row}">
          <span >{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      
      <!--
      <el-table-column
        :label="t('message.layout.managementUnit')"
        width="105px"
      >
        <template #default="{row}">
          <span style="color: red">{{ row.author }}</span>
        </template>
      </el-table-column>
      -->
      
      <el-table-column
        :label="t('message.layout.location')"
        align="center"
        width="200"
      >
        <template #default="{row}">
          <span
            v-if="row.pageviews"
            class="link-type"
            @click="handleGetPageviews(row.pageviews)"
          >{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.area')"
        class-name="status-col"
        width="100"
      >
        <template #default="{row}">
          <el-tag :type="row.status">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        width="200px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.fullContent }}</span>
        </template>
      </el-table-column>
      
      <el-table-column
        :label="t('message.layout.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template #default="{row, $index}">
          <el-button
          	
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            {{ t("message.layout.edit") }}
          </el-button>  
          
          <el-button            
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            {{ t("message.layout.draft") }}
          </el-button>
          
          <el-button
            v-if="row.status !== 'deleted'"            
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ t("message.layout.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="listQuery.currentPage"
      v-model:limit="listQuery.pageCount"
      @current-change="handleCurrentChange"
      layout="total,prev, pager, next, jumper"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempArticleModel"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
      <!--
        <el-form-item
          :label="t('message.layout.author')"
          prop="type"
        >
          <el-select
            v-model="tempArticleModel.type"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.displayName"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        -->
        <el-form-item
          :label="t('message.layout.title')"
          prop="title"
        >
          <el-input v-model="tempArticleModel.title"  placeholder="名称为唯一标示,必须与已有不同" />
        </el-form-item>

        <el-form-item
          :label="t('message.layout.reviewer')"
          prop="reviewer"
        >
          <el-input
            v-model="tempArticleModel.reviewer"            
            placeholder="填写"
          />
        </el-form-item>
        
        <el-form-item
          :label="t('message.layout.phone')"
          prop="timestamp"
        >
          <el-input
            v-model="tempArticleModel.timestamp"            
            placeholder="填写"
          />
        </el-form-item>        
        
        <el-form-item :label="t('message.layout.area')" prop="status">
          <el-select
            v-model="tempArticleModel.status"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!--
        <el-form-item :label="t('message.layout.managementUnit')">
          <el-select
            v-model="tempArticleModel.author"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in importanceOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>       
        -->
        <el-form-item :label="t('message.layout.location')"  prop="pageviews">
          <el-input
            v-model="tempArticleModel.pageviews"
            :autosize="{minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="位置信息"
          />
        </el-form-item>
        <el-form-item label="备注" prop="fullContent">
          <el-input
            v-model="tempArticleModel.fullContent"
            :autosize="{minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder=" 信息"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ t("message.layout.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ t("message.layout.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-model:visible="dialogPageviewsVisible"
      title="Reading statistics"
    >
      <el-table
        :data="pageviewsData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          prop="key"
          label="Channel"
        />
        <el-table-column
          prop="pageviews"
          label="Pageviews"
        />
      </el-table>
      <span class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogPageviewsVisible = false"
        >{{
          t("message.layout.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang='ts'>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  unref
} from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  deleteArticleByName,
  updateArticle,
  defaultArticleModel,
  ArticleType
} from '/@/request/articles'
import { ArticleModel } from '/@/model/articleModel'

//import { exportJson2Excel } from '@/utils/excel'
//import { formatJson } from '@/utils'
import { useI18n } from 'vue-i18n'
//import zhihuiJigouJson from '/@/mock/jijieDian.json';
// import Pagination from '@/components/Pagination/index.vue'
import '/@/assets/iconfont/iconfont.css'
import { useRouter } from 'vue-router';
import { useStore } from '/@/store/index';
import Assert from '/@/utils/shf/Assert'

export default defineComponent({
  components: {
    // Pagination
  },
  setup() {
     let allData:any[] = [];
  	const store=useStore();
    const { t } = useI18n()
    const router = useRouter()
    const calendarTypeOptions = [
      { key: '枪弹', displayName: '枪支弹药' },
      { key: '后勤', displayName: '后勤伙食保障' },
      { key: '车船', displayName: '车船设备' },
      { key: '油气', displayName: '油气资源' },
      { key: '通信', displayName: '通信设施' },
      { key: '战术', displayName: '战术战备' }
    ]

    const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string }
    const dataForm = ref(ElForm)
    const dataMap = reactive({
      tableKey: 0,
      list: Array<ArticleModel>(),
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageCount: 10,
        importance: '疏散路线',
        title: undefined,
        type: undefined,
        sort: undefined
      },

      importanceOptions: ['市人防办', '市防疫局', '区人防办'],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      statusOptions: ['市人防', '市防疫', '区人防'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },

      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      tempArticleModel: defaultArticleModel,
      handleCurrentChange(page?: any) {
        dataMap.listQuery.currentPage = page;
        dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
      },
      handleSizeChange(val: any) {
        dataMap.getList(null, null, val)
      },
      async getList(page?: any, total?: any, limit?: any,data?:any) {
        if (page) {
          dataMap.listQuery.currentPage = page
        }
        if (limit) {
          dataMap.listQuery.pageCount = 10;//limit
        }
        console.log(total)
        dataMap.listLoading = true

        if (data){
        	dataMap.list = data.data
        	dataMap.total = data.total
        }
        else{
              const data:any = await getArticles(dataMap.listQuery,ArticleType.SSYS)
              //const data=zhihuiJigouJson
              let nameArr=[];
              let filterData=[];
              let idx=0;
              if (data){
                for (let i=0;i<data.data.length;i++){
                  if (nameArr.indexOf(data.data[i].title)==-1){
                    nameArr.push(data.data[i].title);
                    filterData.push(data.data[i]);        			
                  }
                }
              }
              dataMap.list = [];
              if(data)
              {
                allData =filterData;
                dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
              }
              dataMap.total = filterData.length ?filterData.length : 0;
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          dataMap.listLoading = false
        }, 0.5 * 1000)
      },
      handleFilter() {
        dataMap.listQuery.currentPage = 1
        dataMap.getList()
      },
      handleModifyStatus(row: any, status: string) {
      /*
        ElMessage.success({
          message: '操作成功',
          type: 'success'
        })
        row.status = status*/
        let jumpData = { type: dataMap.listQuery.importance,name:row.title,lng:row.sourceURL,lat:row.imageURL};
        router.push({
					path: '/menu/menu1/menu12/menu127',
					query: jumpData,
				})
      },
      sortChange(data: any) {
        const { prop, order } = data
        if (prop === 'id') {
          dataMap.sortByID(order)
        }
      },
      sortByID(order: string) {
        if (order === 'ascending') {
          dataMap.listQuery.sort = '+id'
        } else {
          dataMap.listQuery.sort = '-id'
        }
        dataMap.handleFilter()
      },
      getSortClass(key: string) {
        const sort = dataMap.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      resetTempArticleModel() {
        dataMap.tempArticleModel = cloneDeep(defaultArticleModel)
      },
      handleCreate() {
      /*
        console.log('添加了')
        dataMap.resetTempArticleModel()
        dataMap.dialogStatus = 'create'
        dataMap.dialogFormVisible = true
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })*/
       
            router.push({
              path: '/menu/menu1/menu12/menu127',
              query: { type: dataMap.listQuery.importance,name:''},					
        })
      },
      createData() {
      /*
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const ArticleModel = dataMap.tempArticleModel
            //ArticleModel.id = Math.round(Math.random() * 100) + 1024 // mock a id
            //ArticleModel.author = 'RCYJ_Scy'
            console.log(ArticleModel)
            const addData=await createArticle(ArticleModel,ArticleType.SSYS).then(async() => {
		        ElMessage.success('添加成功')
		        dataMap.dialogFormVisible = false
		        const data = await getArticles(dataMap.listQuery,ArticleType.SSYS)
		        //const data=zhihuiJigouJson        
		        dataMap.list = data?.data ?? []
		        dataMap.total = data?.total ?? 0
		      }).catch(err => {
		      ElMessage.warning('添加错误')
		     });
		     
			
            if (addData?data.id) {
              alert(addData.data.id)
              console.log(addData)
              dataMap.list.unshift(addData.data)
            }
			
            dataMap.dialogFormVisible = false
            ElMessage.success({
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            
          }
        })*/
      },

      handleUpdate(row: any) {
        dataMap.tempArticleModel = Object.assign({}, row)
        /*dataMap.tempArticleModel.timestamp = +new Date(
          dataMap.tempArticleModel.timestamp
        )*/
        dataMap.dialogStatus = 'update'
        dataMap.dialogFormVisible = true
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      updateData() {
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const tempData = Object.assign({}, dataMap.tempArticleModel)
            //tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            console.log(tempData)
            const res = await updateArticle(tempData,ArticleType.SSYS);
            if(!res)
            {
                ElMessage.success('更新成功');
                dataMap.dialogFormVisible = false;
                const data = await getArticles(dataMap.listQuery,ArticleType.SSYS);
                let nameArr=[];
                let filterData=[];
                let idx=0;
                if (data){
                  for (let i=0;i<data.data.length;i++){
                    if (nameArr.indexOf(data.data[i].title)==-1){
                      nameArr.push(data.data[i].title);
                      filterData.push(data.data[i]);        			
                    }
                  }
                }
                 dataMap.list = [];
                if(data)
                {
                  allData =filterData;
                  dataMap.list = allData.slice((dataMap.listQuery.currentPage-1)*dataMap.listQuery.pageCount,(dataMap.listQuery.currentPage)*dataMap.listQuery.pageCount);
                }
                dataMap.total = filterData.length ?filterData.length : 0;     
                return;
            }
            Assert.isFalse(true,res+"");
			/*
            console.log(data, '-----------------')
            if (data) {
              const index = dataMap.list.findIndex(
                (v) => v.id === data.data.id
              )
              dataMap.list.splice(index, 1, data.data)
            }

            dataMap.dialogFormVisible = false
            ElMessage.success({
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            */
          }
        })
      },
      async handleDelete(row: any, index: number) {
      	await deleteArticleByName(row.title,ArticleType.SSYS).then(()=>{
        ElMessage.success({
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        dataMap.list.splice(index, 1)
        }).catch(err => {
	      ElMessage.warning('删除失败')
	     });
      },
      async handleGetPageviews(pageviews: string) {
        const data = await getPageviews({ pageviews })
        //const data = zhihuiJigouJson.data;
        dataMap.pageviewsData = data?.data.pageviews
        console.log(dataMap.pageviewsData)
        dataMap.dialogPageviewsVisible = true
      },
      handleDownload() {
        dataMap.downloadLoading = true
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        //const data = formatJson(filterVal, dataMap.list)
        //exportJson2Excel(tHeader, data, 'table-list')
        dataMap.downloadLoading = false
      },
      typeFilter: (type: string) => {
        return calendarTypeKeyValue[type]
      }
    })
    onMounted(() => {
      console.log(typeof ElForm)
      dataMap.getList(null, null, 10)
    })
    return { t,...toRefs(dataMap), dataForm }
  }
})
</script>
